import sys

from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QApplication, QMainWindow, QMessageBox, QFileDialog

from consoledialog import ConsoleDialog
from gameframe import UnshufflerGameFrame, ImagePixmapItem
from menubar import UnshufflerMenuBar
from settings import Settings
from statusbar import UnshufflerStatusBar

from imagemanipulation import *

class Unshuffler(QtGui.QWidget):
    def __init__(self, parent = None):
        QMainWindow.__init__(self, None)
        self.parent = parent
        self.setWindowTitle('Unshuffler')
        
        ## Create widgets
        self.menu_bar = UnshufflerMenuBar(self)
        self.menu_bar.setFixedHeight(25)
        self.status_bar = UnshufflerStatusBar(self)
        self.status_bar.setFixedHeight(45)
        
        ## Application settings
        self.settings = Settings(self)
        self.image = self.settings.image
        
        ## Redirect stdout,stderr to built-in dialog
        self.console = ConsoleDialog(sys.stdout)
        sys.stdout = self.console
        sys.stderr = self.console
        
        ## Create Game Controls
        self.game_frame = UnshufflerGameFrame(self)
        
        ## Create Layout
        vbox = QtGui.QVBoxLayout(self)
        vbox.addWidget(self.menu_bar)
        vbox.addWidget(self.game_frame)
        vbox.addWidget(self.status_bar)
        self.setLayout(vbox)
        
        self.setMinimumWidth(1024)
        self.setMinimumHeight(768)
        self.resize(1024,768)
        vbox.setContentsMargins(5,5,5,5)

        self.reallyLoadImage(self.image)
        
    def about(self):
        msg = '''
<b>Unshuffler, %s</b>
<p>
Unshuffler is a game in which the player must unshuffle the
images before the time runs out. The player can provide his/her
own images for the game, and can alter game options to change
the difficulty and game style.
</p>
''' % self.settings.version

        mb = QMessageBox(self)
        mb.setText(msg.strip())
        mb.setIcon(QtGui.QMessageBox.Information)
        mb.setWindowTitle('Unshuffler')
        mb.show()
        
    def changeSettings(self):
        self.settings.show()
        
    def console(self):
        self.console.show()
        
    def help(self):
        msg = '''
Don't Panic!
'''
        mb = QMessageBox(self)
        mb.setText(msg.strip())
        mb.setIcon(QtGui.QMessageBox.Question)
        mb.setWindowTitle('Help')
        mb.show()

    def reallyLoadImage(self, path):
        self.image = str(path)
        self.game_frame.initGame(self.image, True)
        self.status_bar.showMessage(self.image, 3500)

    def loadImage(self):
        filedialog = QtGui.QFileDialog()
        path = filedialog.getOpenFileName(None, 'Open image file...', '')
        self.reallyLoadImage(path)    
    
    def toggle_fullscreen(self):
        if self.isFullScreen():
            self.showNormal()
        else:
            self.showFullScreen()
